'use strict';

const Service = require('egg').Service;
class KnowledgeService extends Service {
    async delete(data) {
        try {
            await this.app.mysql.delete('knowledge', {
                phone: data.phone,
                id: data.id
            })
            return {
                code: 1,
                msg: '删除成功'
            }
        } catch (e) {
            return {
                code: 0,
                msg: e.message
            }
        }
    }
    
    async list(phone) {
        try {
            const result = await this.app.mysql.select('knowledge', {
                where: {
                    phone: phone
                }
            })
            return {
                code: 1,
                data: result
            }
        } catch(e) {
            return {
                code: 0,
                msg: e.message
            }
        }
    }
    async add(data) {
        try {
            // name查重
            const searchResult = await this.app.mysql.select('knowledge', {
                where: {
                    name: data.name,
                    phone: data.phone,
                    type: data.type
                }
            })
            if (searchResult.length > 0) {
                return {
                    code: 0,
                    msg: '该知识库已存在，请重新命名'
                }
            } else {
                // 数据库的插入
                await this.app.mysql.insert('knowledge', {
                    name: data.name,
                    detail: data.detail,
                    type: data.type,
                    phone: data.phone
                })
                const result = await this.app.mysql.select('knowledge', {
                    where: {
                        name: data.name,
                        phone: data.phone,
                        type: data.type
                    }
                })
                console.log('result', result)
                return {
                    code: 1,
                    id: result[0].id,
                    msg: '添加成功'
                }
            }
        } catch(e) {
            return {
                code: 0,
                msg: e.message
            }
        }
    }
}

module.exports = KnowledgeService;
